package com.swt.draw.config.jndi;

import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.apache.tomcat.util.descriptor.web.ContextResource;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jndi.JndiObjectFactoryBean;

import javax.naming.NamingException;
import javax.sql.DataSource;

@Configuration
public class JndiDatasourceCfg {

        @Bean
        public TomcatServletWebServerFactory tomcatFactory() {
            return new TomcatServletWebServerFactory() {
                @Override
                protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
                    tomcat.enableNaming();
                    return super.getTomcatWebServer(tomcat);
                }

                @Override
                protected void postProcessContext(Context context) {
                    ContextResource resource = new ContextResource();
                    resource.setType(DataSource.class.getName());
                    resource.setAuth("Container");
                    resource.setName("jdbc/dgjxzy");
                    resource.setProperty("maxActive", "100");
                    resource.setProperty("maxIdle", "20");
                    resource.setProperty("maxWait", "10000");
                    resource.setProperty("factory", BasicDataSourceFactory.class.getName());
                    resource.setProperty("driverClassName", "oracle.jdbc.driver.OracleDriver");
                    resource.setProperty("url", "jdbc:oracle:thin:@127.0.0.1:1521:orcl");
//                    resource.setProperty("url", "jdbc:oracle:thin:@127.0.0.1:1521:helowin");
                    resource.setProperty("username", "OLIVER");
//                    resource.setProperty("username", "system");
                    resource.setProperty("password", "123456");
                    context.getNamingResources().addResource(resource);
                }
            };
        }

        @Bean
        public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
            JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
            bean.setJndiName("java:/comp/env/jdbc/dgjxzy");
            bean.setProxyInterface(DataSource.class);
            bean.setLookupOnStartup(false);
            bean.afterPropertiesSet();
            return (DataSource) bean.getObject();
        }
}
